package com.concurrent.threadpool;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @Date 2020/7/13 17:31
 * @Author admin
 * @Description
 */
public class CompletableFutureDemo {
    //任務1 洗水壶->烧开水
    CompletableFuture<Void> f1 = CompletableFuture.runAsync(()->{
        System.out.println("T1洗水壺...");
        sleep(1,TimeUnit.SECONDS);
        System.out.println("T1:烧开水...");
        sleep(15,TimeUnit.SECONDS);
    });
    //任務2 洗茶壶->洗茶杯->拿茶叶 1 2 1
    CompletableFuture<String> f2 = CompletableFuture.supplyAsync(()->{
        System.out.println("T2:洗茶壺：....");
        sleep(1,TimeUnit.SECONDS);
        System.out.println("T2:洗茶杯：....");
        sleep(2,TimeUnit.SECONDS);
        System.out.println("T2:拿茶叶：....");
        sleep(1,TimeUnit.SECONDS);
        return "龍井";
    });

    private void sleep(int t,TimeUnit unit) {
        try {
            unit.sleep(t);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    //任務3 任务1和任务2完成后执行：泡茶
    CompletableFuture<String> f3 = f1.thenCombine(f2,(__,tf)->{
        System.out.println("拿到茶葉："+tf);
        System.out.println("T3泡茶...");
        return "上茶："+tf;
    });

    //or 的汇聚关系的使用
    CompletableFuture<String> f4 = CompletableFuture.supplyAsync(
            ()->{
                int t = new Random().nextInt(10);
                sleep(t,TimeUnit.SECONDS);
                return String.valueOf(t);
            }
    );

    CompletableFuture<String> f5 = CompletableFuture.supplyAsync(
            ()->{
                int t = new Random().nextInt(10);
                sleep(t,TimeUnit.SECONDS);
                return String.valueOf(t);
            }
    );
    CompletableFuture f6 = f4.applyToEither(
            f5,s -> s
    );


    public static void main(String[] args) {
//        CompletableFutureDemo demo = new CompletableFutureDemo();
//        System.out.println(demo.f3.join());

        CompletableFutureDemo demo1 = new CompletableFutureDemo();
        System.out.println(demo1.f6.join());

    }
}
